/*
 * Copyright 2012 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.dspl.xml;

import com.google.common.base.Preconditions;
import com.google.dspl.jaxb.Dspl;
import com.google.dspl.model.Dataset;
import com.google.dspl.validate.DatasetResolver;

/**
 * Converts a JAXB {@link Dspl} object to a {@link Dataset}. Uses a {@link NamespaceMapping} to
 * resolve references to external datasets. Will throw an error during conversion if there is an
 * external reference that is not present in the mapping.
 *
 * @author Shardul Deo
 */
public class DsplToDatasetConverter {

  /**
   * Static utility method to convert a DSPL that does not have any external references. For proper
   * conversion of DSPLs that have external references, construct a converter using
   * {@link #DsplToDatasetConverter(DatasetResolver, NamespaceMapping)}.
   *
   * @param dspl The DSPL that needs to be converted
   * @param datasetId The id of the resulting dataset
   */
  public static Dataset convertDspl(Dspl dspl, String datasetId) {
    return new DsplToDatasetConversion(
        new DatasetResolver(), new NamespaceMapping(), dspl, datasetId).convert();
  }

  private final DatasetResolver datasetResolver;
  private final NamespaceMapping namespaceMapping;

  /**
   * @param datasetResolver Used for resolving references to external concepts.
   * @param namespaceMapping Mapping between dataset namespaces and their ids. If the DSPL being
   *        converted contains references to external namespaces, this map must contain a mapping
   *        for them.
   */
  public DsplToDatasetConverter(DatasetResolver datasetResolver,
      NamespaceMapping namespaceMapping) {
    this.datasetResolver = Preconditions.checkNotNull(datasetResolver);
    this.namespaceMapping = Preconditions.checkNotNull(namespaceMapping);
  }

  /**
   * @param dspl The DSPL that needs to be converted
   * @param datasetId The id of the resulting dataset
   */
  public Dataset convert(Dspl dspl, String datasetId) {
    return new DsplToDatasetConversion(datasetResolver, namespaceMapping, dspl, datasetId)
        .convert();
  }
}
